package cn.stylefeng.mferp.config.datasource;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取链接
 */
public class LinkConfig {

    //存储所有链接（JdbcTemplate 或者 MongoTemplate）
    private static Map<String, Object> linkMap = new HashMap<>();

    public static JdbcTemplate jdbcTemplate = null;
    static {//配置在application-config.yml中，初始的数据库链接
        if(jdbcTemplate == null) {
            try {
                String url = YmlConfigUtil.getConfigByKey("url");
                String username = YmlConfigUtil.getConfigByKey("username");
                String password = YmlConfigUtil.getConfigByKey("password");
                String driverClassName = YmlConfigUtil.getConfigByKey("driver-class-name");

                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName(driverClassName);
                dataSource.setUrl(url);
                dataSource.setUsername(username);
                dataSource.setPassword(password);
                jdbcTemplate = new JdbcTemplate(dataSource);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 获取Jdbctemplate
     * @param name
     * @return
     */
    public static JdbcTemplate getJdbcTemplate(String name) {
        JdbcTemplate jdbcTemplate1 = (JdbcTemplate) linkMap.get(name);
        if(jdbcTemplate1 == null) {
            String query = "select `driver` 'dbDriver',`url` 'dbUrl',`username` 'dbUserName',`password` 'dbPassword' from `td_ds_rmdb` where db_type = 'MySQL' and `link_name` = '" + name + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(query);
            if (list != null && list.size() > 0) {
                Map<String, Object> map = list.get(0);
                System.out.println(JSON.toJSONString(map));
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName(map.get("dbDriver").toString());
                dataSource.setUrl(map.get("dbUrl").toString());
                dataSource.setUsername(map.get("dbUserName").toString());
                dataSource.setPassword(map.get("dbPassword").toString());
                jdbcTemplate1 = new JdbcTemplate(dataSource);
                linkMap.put(name, jdbcTemplate1);
            }
        }
        return jdbcTemplate1;
    }

//    public static MongoTemplate getMongoTemplate(String name) {
//        MongoTemplate mongoTemplate = (MongoTemplate) linkMap.get(name);
//        if(mongoTemplate == null) {
//            String query = "select `url` 'dbUrl',`username` 'dbUserName',`password` 'dbPassword', `db_name` 'dbName' from `td_ds_rmdb` where db_type = '"+ Const.MONGODB +"' and `link_name` = '" + name + "'";
//            //String query = "select db_url 'dbUrl',db_user_name 'dbUserName',db_password 'dbPassword',mongodb_port 'mongodbPort',mongodb_database 'mongodbDatabase' from code_dbinfo where db_type = '1' and `name` = '" + name + "'";
//            List<Map<String, Object>> list = jdbcTemplate.queryForList(query);
//            if (list != null && list.size() > 0) {
//                try {
//                    MongoDbFactory mongoDbFactory = null;
//                    Map<String, Object> map = list.get(0);
//                    String url = map.get("dbUrl").toString();//配置时，mongodb的地址和端口写在同一个字段，用斜杠分隔
//                    String port = url.split("/")[1];//mongodb端口号
//                    url = url.split("/")[0];//mongodb地址
//                    boolean tf="".equals(map.get("dbUserName").toString())||"".equals(map.get("dbPassword").toString());
//                    if(tf){
//                        mongoDbFactory= new SimpleMongoDbFactory(new MongoClient(url, Integer.parseInt(port)), map.get("dbName").toString());
//                    }else {
//                        ServerAddress serverAddress = new ServerAddress(url, Integer.parseInt(port));
//                        List<MongoCredential> credentialsList = new ArrayList<>();
//                        credentialsList.add(MongoCredential.createCredential(map.get("dbUserName").toString(), map.get("dbName").toString(), map.get("dbPassword").toString().toCharArray()));
//                        mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(serverAddress, credentialsList), map.get("dbName").toString());
//                    }
//                    mongoTemplate = new MongoTemplate(mongoDbFactory);
//                    linkMap.put(name, mongoTemplate);
//                } catch (Exception e) {
//
//                }
//            }
//        }
//        return mongoTemplate;
//    }

    /**
     * 删除JdbcTemplate
     * @param name
     */
    public static void deleteJdbcTemplateInMap(String name) {
        JdbcTemplate jdbcTemplate1 = (JdbcTemplate) linkMap.get(name);
        if(jdbcTemplate1 != null) {
            linkMap.remove(name);
        }
    }

    /**
     * 删除MongoTemplate
     * @param name
     */
//    public static void deleteMongoTemplateInMap(String name) {
//        MongoTemplate mongoTemplate = (MongoTemplate) linkMap.get(name);
//        if(mongoTemplate != null) {
//            linkMap.remove(name);
//        }
//    }

    /**
     * 清空linkMap
     */
    public static void clearLinkMap() {
        if(linkMap != null) {
            linkMap.clear();
        }
    }

    /**
     * 返回数据库连接
     * 针对Oracle
     * @param name
     * @return
     */
    public static Connection getConnection(String name) {
        Connection conn = (Connection) linkMap.get(name);
        if(conn == null) {
            try {
                String query = "select `driver` 'dbDriver',`url` 'dbUrl',`username` 'dbUserName',`password` 'dbPassword' from `td_ds_rmdb` where db_type = 'Oracle' and `link_name` = '" + name + "'";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(query);

                if (list != null && list.size() > 0) {
                    Map<String, Object> map = list.get(0);

                    String url = map.get("dbUrl").toString();
                    String user = map.get("dbUserName").toString();
                    String password = map.get("dbPassword").toString();
                    String driver = StringUtils.isBlank(map.get("dbDriver").toString()) ? "oracle.jdbc.driver.OracleDriver" : map.get("dbDriver").toString();
                    conn = ConUtil.getConnection(url, user, password, driver);
                    linkMap.put(name, conn);
                    return conn;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return conn;
    }
}
